package com.tnovoselec.server.gdjejefrka.util;

import java.io.OutputStream;
import java.util.Map;

import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

/**
 * Adapter Gateway - Util <b />
 * 
 * @author Tomica Bosnjak
 * @version 1.1.0
 * @since 1.0.0
 */
public class AdapterXMLUtil {

	public static void serialize(Source source, OutputStream out, Map<String, String> outputProperties) throws Exception {
		try {
			Transformer transformer = TransformerFactory.newInstance().newTransformer();
			for (Map.Entry<String, String> entry : outputProperties.entrySet()) {
				transformer.setOutputProperty(entry.getKey(), entry.getValue());

			}

			transformer.transform(source, new StreamResult(out));

		} catch (TransformerConfigurationException ex) {
			throw new Exception("XML document to output stream error.", ex);
		} catch (TransformerException ex) {
			throw new Exception("XML document to output stream error.", ex);
		}
	}

	public static Element createCDATAElement(Document document, String elementName, String elemValue, Element parent) {
		Element element = XMLUtil.createElement(document, elementName, parent);
		if (elemValue != null) {
			element.appendChild(document.createCDATASection(elemValue));
		}
		return element;
	}

	public static void removeNode(Node parent, Node child) {
		while (child.hasChildNodes()) {
			child.removeChild(child.getFirstChild());
		}

		Node sibling = child.getNextSibling();
		if (sibling != null) {
			if (sibling.getNodeType() == Node.TEXT_NODE) {
				String txtNode = sibling.getNodeValue().trim();
				if (txtNode.equals("")) {
					parent.removeChild(sibling);
				}
			}
		}
		parent.removeChild(child);
	}

	@SuppressWarnings(value = "all")
	public static Document compact(Document document, String encoding) throws Exception {
		if (document == null) {
			throw new Exception("Document is empty!");
		}
		encoding = Util.isEmpty(encoding) ? Util._encoding : encoding;

		try {
			document.normalize();
			String source = XMLUtil.serialize(document, encoding);
			source = source.replaceAll(">[ \t\n\\x0B\f\r]+<", "><");
			source = source.replaceAll("[\n\r]+", "");

			return XMLUtil.getDoc(source.getBytes(encoding));
		} catch (Throwable t) {
			throw new Exception(t.getMessage(), t);
		}
	}

	public static String getChildNodeValue(Node item, String childName) {
		Node node = XMLUtil.findNode(item, childName);
		if (null == node) {
			return null;
		}
		return XMLUtil.getNodeValue(node);
	}
}
